package com.example.customer01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.customer01.mapper.CourseMapper;
import com.example.customer01.mapper.StudentCourseMapper;
import com.example.customer01.pojo.Course;
import com.example.customer01.pojo.StudentCourse;
import com.example.customer01.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 课程服务实现类
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private StudentCourseMapper studentCourseMapper;

    @Override
    @Transactional
    public Course createCourse(Course course) {
        // 检查课程代码是否已存在
        Course existingCourse = getCourseByCode(course.getCourseCode());
        if (existingCourse != null) {
            throw new RuntimeException("课程代码已存在");
        }
        
        // 设置初始状态
        course.setStatus("ACTIVE");
        course.setDeleted(0);
        
        // 保存课程
        save(course);
        return course;
    }

    @Override
    @Transactional
    public boolean deleteCourse(Integer id) {
        Course course = getById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        
        // 使用 MyBatis-Plus 的逻辑删除
        return removeById(id);
    }

    @Override
    @Transactional
    public Course updateCourse(Course course) {
        Course existingCourse = getById(course.getId());
        if (existingCourse == null) {
            throw new RuntimeException("课程不存在");
        }
        
        // 如果修改了课程代码，需要检查是否重复
        if (!existingCourse.getCourseCode().equals(course.getCourseCode())) {
            Course codeExists = getCourseByCode(course.getCourseCode());
            if (codeExists != null) {
                throw new RuntimeException("课程代码已存在");
            }
        }
        
        updateById(course);
        return course;
    }

    @Override
    public Course getCourseById(Integer id) {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getId, id)
               .eq(Course::getDeleted, 0);
        return getOne(wrapper);
    }

    @Override
    public List<Course> getAllCourses() {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getDeleted, 0);
        return list(wrapper);
    }

    @Override
    public Course getCourseByCode(String courseCode) {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getCourseCode, courseCode)
               .eq(Course::getDeleted, 0);
        return getOne(wrapper);
    }

    @Override
    public IPage<Course> getCoursePage(Page<Course> page, String keyword) {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getDeleted, 0);
        
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(Course::getCourseName, keyword)
                            .or()
                            .like(Course::getCourseCode, keyword)
                            .or()
                            .like(Course::getTeacher, keyword));
        }
        
        wrapper.orderByDesc(Course::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    public List<Course> getCoursesByStudentId(Integer studentId) {
        return courseMapper.findCoursesWithStudents(studentId);
    }

    @Override
    @Transactional
    public boolean enrollStudent(Integer studentId, Integer courseId, String semester) {
        Course course = getById(courseId);
        if (course == null || !"ACTIVE".equals(course.getStatus())) {
            return false;
        }

        // 检查是否已经选过这门课
        LambdaQueryWrapper<StudentCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentCourse::getStudentId, studentId)
               .eq(StudentCourse::getCourseId, courseId)
               .eq(StudentCourse::getSemester, semester);
        StudentCourse existingEnrollment = studentCourseMapper.selectOne(wrapper);
        if (existingEnrollment != null) {
            return false;
        }

        int enrolledCount = studentCourseMapper.countEnrolledStudents(courseId);
        if (enrolledCount >= course.getMaxStudents()) {
            return false;
        }

        StudentCourse studentCourse = new StudentCourse();
        studentCourse.setStudentId(studentId);
        studentCourse.setCourseId(courseId);
        studentCourse.setStatus("ENROLLED");
        studentCourse.setSemester(semester);

        return studentCourseMapper.insert(studentCourse) > 0;
    }

    @Override
    @Transactional
    public boolean dropCourse(Integer studentId, Integer courseId) {
        LambdaQueryWrapper<StudentCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentCourse::getStudentId, studentId)
               .eq(StudentCourse::getCourseId, courseId);
        
        StudentCourse studentCourse = studentCourseMapper.selectOne(wrapper);
        if (studentCourse == null || "DROPPED".equals(studentCourse.getStatus())) {
            return false;
        }

        studentCourse.setStatus("DROPPED");
        return studentCourseMapper.updateById(studentCourse) > 0;
    }

    @Override
    @Transactional
    public boolean updateGrade(Integer studentId, Integer courseId, String grade) {
        // 验证成绩格式
        if (!isValidGrade(grade)) {
            return false;
        }

        LambdaQueryWrapper<StudentCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentCourse::getStudentId, studentId)
               .eq(StudentCourse::getCourseId, courseId);
        
        StudentCourse studentCourse = studentCourseMapper.selectOne(wrapper);
        if (studentCourse == null) {
            return false;
        }

        studentCourse.setGrade(grade);
        return studentCourseMapper.updateById(studentCourse) > 0;
    }

    /**
     * 验证成绩格式是否有效
     * @param grade 成绩
     * @return 是否有效
     */
    private boolean isValidGrade(String grade) {
        if (grade == null || grade.trim().isEmpty()) {
            return false;
        }
        
        // 允许的成绩格式：0-100的整数，或者A+、A、A-、B+、B、B-、C+、C、C-、D+、D、D-、F
        String pattern = "^([0-9]|[1-9][0-9]|100)$|^([A-D][+-]?|F)$";
        return Pattern.matches(pattern, grade.trim());
    }
} 